package study.saas.order.service.Impl;

import com.opencsv.CSVWriter;
import org.springframework.stereotype.Service;
import study.saas.order.entity.Order;
import study.saas.order.repo.OrderRepository;
import study.saas.order.service.OrderService;
import study.saas.order.service.model.OrderCriteria;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderRepository orderRepository;

    //业务一：创建订单
    @Override
    public Order createOrder(Order order) {
        return orderRepository.save(order);
    }

    //业务二：订单查询
    @Override
    public Order findById(Long orderId) {
        return orderRepository.findById(orderId)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
    }

    //业务三:订单条件查询
    @Override
    public List<Order> findOrdersByCriteria(OrderCriteria criteria) {
        // 根据传入的条件进行查询
        if (criteria.getOrderNumber() != null) {
            return orderRepository.findByOrderNumberContaining(criteria.getOrderNumber());
        } else if (criteria.getUserId() != null && criteria.getStatus() != null) {
            return orderRepository.findByUserIdAndStatus(criteria.getUserId(), criteria.getStatus());
        } else if (criteria.getPaymentStatus() != null) {
            return orderRepository.findByPaymentStatus(criteria.getPaymentStatus());
        } else if (criteria.getStartDate() != null && criteria.getEndDate() != null) {
            return orderRepository.findByCreateTimeBetween(criteria.getStartDate(), criteria.getEndDate());
        }

        // 如果没有条件则返回空列表或可以做其他处理
        return List.of();
    }

    //业务四：导出订单
    @Override
    public File exportOrders(OrderCriteria criteria) {
        // 1. 查询符合条件的订单
        List<Order> orders = findOrdersByCriteria(criteria);

        // 2. 导出订单数据为 CSV
        File file = new File("orders_export.csv");

        try (CSVWriter writer = new CSVWriter(new FileWriter(file))) {
            // 写入 CSV 文件头
            writer.writeNext(new String[]{"Order ID", "User ID", "Status", "Payment Status", "Create Time"});

            // 遍历订单列表，写入每一行数据
            for (Order order : orders) {
                writer.writeNext(new String[]{
                        String.valueOf(order.getOrderId()),
                        String.valueOf(order.getUser().getUserId()),
                        order.getStatus().name(),
                        order.getPaymentStatus().name(),
                        order.getCreatedAt().toString()
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return file;
    }

}

